package com.springboot.frame.socket.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: NettyServer
 * @Author: liheng
 * @Date: 2018/9/25 15:40
 * @Description:
 */
@Slf4j
@Component
public class ServerNetty implements InitializingBean, DisposableBean {

    private final ServerNettyChannelInitializer serverNettyChannelInitializer;


    private int port = 9000;

    private EventLoopGroup bossGroup = null;

    private EventLoopGroup group = null;

    private ChannelFuture cf = null;

    @Autowired
    public ServerNetty(ServerNettyChannelInitializer serverNettyChannelInitializer) {
        this.serverNettyChannelInitializer = serverNettyChannelInitializer;
    }

    /**
     * 启动服务端
     *
     * @throws Exception
     */
    public void start() {
        bossGroup = new NioEventLoopGroup();
        group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            // 绑定线程池
            b.group(group, bossGroup)
                    // 指定使用的channel
                    .channel(NioServerSocketChannel.class)
                    //保持长连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(serverNettyChannelInitializer);
            //绑定端口，同步等待成功
            cf = b.bind(port).sync();
            log.info(ServerNetty.class + " 服务器Socket启动正在监听： " + cf.channel().localAddress());
            //等待服务器监听端口关闭,TODO 不要这行代码，与springboot集成会出问题
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error(ServerNetty.class + " 服务器Socket启动失败： " + e.getMessage());
        } finally {
            //释放线程池资源
            bossGroup.shutdownGracefully();
            group.shutdownGracefully();
        }
    }

    @Override
    public void destroy() throws Exception {
        // 关闭服务器通道
        if (cf != null) {
            cf.channel().closeFuture().sync();
        }
        // 释放资源
        if (bossGroup != null) {
            bossGroup.shutdownGracefully().sync();
        }
        if (group != null) {
            group.shutdownGracefully().sync();
        }
    }


    @Override
    public void afterPropertiesSet() {
        start();
    }

}
